<template>
  <div class="comment">
    <van-field
      class="my-field"
      v-model="message"
      rows="2"
      autosize
      label="发表评论"
      type="textarea"
      maxlength="50"
      show-word-limit
      ref="fieldRef"
    />
    <van-button
      type="primary"
      block
      @click="postComment"
    >提交评论</van-button>
    <div class="comment-list">
      <van-card
        :desc="item.content"
        v-for="(item,index) in comments"
        :key="index"
      >
        <template #thumb>
          <div>
            <van-icon name="https://b.yzcdn.cn/vant/icon-demo-1126.png" />
            <div>{{item.user_name}}</div>
          </div>
        </template>
        <template #title>
          <van-rate
            v-model="item.rate"
            readonly
          />
        </template>
        <template #price>
          <span> {{item.add_time}}</span>
        </template>
      </van-card>
      <van-loading
        class="more"
        v-if="loading"
      >加载中...</van-loading>

      <button
        v-else
        class="more btn"
        @click="getMore"
        :disabled="hasMore"
      >{{hasMore?'被掏空了':'加载更多'}}</button>
    </div>
  </div>

</template>
<script>
export default {
  props: ['id'],
  data() {
    return {
      message: '请输入bb的内容',
      pageNo: 0,
      pageSize: 6,
      comments: [],
      hasMore: false,
      loading: false
    }
  },
  created() {
    this.getComments()
  },
  methods: {
    async getComments() {
      // 节流
      if (this.hasMore !== false) return
      ++this.pageNo
      const res = await this.$http.getComments({ id: this.id, pageNo: this.pageNo, pageSize: this.pageSize })
      this.comments = this.comments.concat(res.data.message)
      // 计算临界点
      this.hasMore = this.pageNo * this.pageSize > res.data.count
    },
    getMore() {
      this.loading = true
      setTimeout(() => {
        this.loading = false
        this.getComments()
      }, 500)
    },
    async postComment() {
      if (!this.message) return
      await this.$http.postComment({ id: this.id, content: this.message })
      this.comments.unshift({
        id: new Date().getTime(),
        user_name: "匿名用户",
        add_time: new Date().getTime(),
        content: this.message,
        rate: 5
      })
      // 清空
      this.message = ''
      // 获取焦点
      this.$refs.fieldRef.focus()
    }
  }
}
</script>
<style lang="scss">
.comment {
  .my-field {
    margin: 10px 0;
    border: 1px solid #ddd;
    .van-cell__title {
      font-size: 16px;
      font-weight: 600;
    }
  }
  .comment-list {
    margin: 10px 0;
    .van-icon__image {
      font-size: 60px;
    }
    .van-card__desc {
      margin-top: 15px;
    }
  }
  .more {
    color: #969799;
    font-size: 12px;
    line-height: 40px;
    text-align: center;
  }
  .btn {
    width: 100%;
    outline: none;
    border: 0;
    background-color: #fff;
  }
}
</style>
